package com.ruoyi.extdata.common;

import com.ruoyi.bizsys.service.IExtTryQueueService;
import com.ruoyi.common.enums.RspEnmu;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.function.Function;

/**
 * 方法重试
 *
 * @author cyh
 */
@Component
@Slf4j
@AllArgsConstructor
public class RetryFunction {

    private IExtTryQueueService tryQueueService;

    /**
     * 接口默认超时3次尝试并计数
     * 对超时TimeOut及非业务异常进行计数
     *
     * @param function
     * @param custNo
     * @param tryType
     * @return
     */
    public Object tryCount(Function function, String custNo, String tryType) {
        int timeOutTryCount = 3;
        while (timeOutTryCount > 0) {
            try {
                return function.apply(null);
            } catch (Exception e) {
                //超时
                if (RspEnmu.NETWORK_BUSY.getMessage().equals(e.getMessage())) {
                    timeOutTryCount--;
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                } else {
                    //接口异常 进入任务
                    tryQueueService.appendQueue(custNo, tryType);
                    throw e;
                }
                //结束重试 进入任务
                if (timeOutTryCount == 0) {
                    tryQueueService.appendQueue(custNo, tryType);
                    throw e;
                }
            }
        }
        return null;
    }

}
